<template>
  <div class="goods-info-model">
    <el-form ref="formRef" :disabled="readonly" :model="formData" label-width="135px" status-icon>
      <el-form-item label="商品模型：">
        <el-select v-model="modelId" :disabled="readonly" clearable filterable placeholder="请选择商品模型" value="">
          <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>

        <el-button-group v-if="!readonly && hasPermission(['shop:goods_model:create', 'shop:goods_model:update'])" size="small" style="margin-left: 6px;margin-top: 6px">
          <el-button v-if="hasPermission('shop:goods_model:create')" icon="circle-plus" type="danger" @click="handleModelFormShow(1 ,0)">新增</el-button>
          <el-button v-if="modelId && modelId > 0 && hasPermission('shop:goods_model:update')" icon="edit" type="primary" @click="handleModelFormShow(2,modelId)">编辑</el-button>
        </el-button-group>
      </el-form-item>

      <!-- 模型项目信息 -->
      <template v-for="spec in formData.spec_list">
        <el-form-item :label="spec.name + '：'">
          <el-checkbox-group v-model="spec.select_ids" :disabled="readonly" @change="generateGoodsSpecData">
            <el-checkbox v-for="item in spec.spec_items" :key="item.id" :value="item.id">
              {{ item.item }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </template>
    </el-form>

    <div v-if="dynamicTableHeaders.length > 0" class="table-wrapper">
      <!-- 规格属性信息 -->
      <el-table :data="tableItemList.slice((pageData.pageNum - 1) * pageData.pageSize, pageData.pageNum * pageData.pageSize)" fit highlight-current-row>

        <el-table-column v-for="(headers, index) in dynamicTableHeaders" :key="headers" :label="headers" fixed min-width="120" show-overflow-tooltip>
          <template #default="scope">
            {{ specItemMap[scope.row.spec_key_ids[index]] }}
          </template>
        </el-table-column>

        <el-table-column key="image_url" align="center" label="图片" prop="image_url" width="66">
          <template #default="scope">
            <UploadImage v-if="scope.row.id >= 0" v-model="scope.row.image_url" :disabled="readonly" :file-size="10" :show-tip="false" height="42px" width="42px"/>
          </template>
        </el-table-column>

        <el-table-column key="price" align="center" label="商品售价" min-width="170" prop="price">
          <template #default="scope">
            <el-input-number v-model="scope.row.price" :disabled="readonly" :min="0" :precision="2" :step="0.01" controls-position="right"/>
          </template>
        </el-table-column>

        <!-- 花朵专区 -->
        <template v-if="goodsType == 4">
          <el-table-column key="price_integral" align="center" label="花朵抵扣" min-width="170" prop="price_integral">
            <template #default="scope">
              <el-input-number v-model="scope.row.price_integral" :disabled="readonly" :min="0" :precision="2" :step="0.01" controls-position="right"/>
            </template>
          </el-table-column>
        </template>

        <el-table-column key="price_cost" align="center" label="供货价格" min-width="170" prop="price_cost">
          <template #default="scope">
            <el-input-number v-model="scope.row.price_cost" :disabled="readonly" :min="0" :precision="2" :step="0.01" controls-position="right"/>
          </template>
        </el-table-column>

        <el-table-column key="store_count" align="center" label="库存" min-width="170" prop="store_count">
          <template #default="scope">
            <el-input-number v-model="scope.row.store_count" :disabled="readonly" :max="88888" :min="0" :step="100" controls-position="right"/>
          </template>
        </el-table-column>

        <el-table-column v-if="!readonly" key="controls" align="center" fixed="right" header-align="center" label="操作" width="105px">
          <template #default="scope">
            <el-button v-if="scope.row.id < 0" link type="primary" @click="handleItemFill(scope.row)">批量填充</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页操作 -->
      <el-pagination v-if="tableItemList.length > 0"
                     :current-page="pageData.pageNum"
                     :page-size="pageData.pageSize"
                     :page-sizes="[10, 30, 50]"
                     :total="tableItemList.length"
                     background
                     class="table-pagination"
                     layout="total, sizes, prev, pager, next"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"/>
    </div>

    <!-- 弹窗操作 -->
    <GoodsModelForm ref="modelFormRef" @refresh="handleRefreshModelData"/>
  </div>
</template>

<script lang="ts" setup>

import { computed, onMounted, PropType, reactive, ref, watch } from 'vue';
import { defGoodsModel, GoodsModel, GoodsModelSpecItem, GoodsSpec, modelInfo, modelUsableList } from '@/api/api-shop.ts';
import { calcDescartes } from '@/utils';
import { hasPermission } from '@/utils/permission.ts';
import GoodsModelForm from '@/views/shop/goods-model/goods-model-form.vue';
import { UploadImage } from '@/components/upload';

const props = defineProps({
  modelValue: {type: Number, default: undefined},
  itemList: {
    type: Array as PropType<GoodsSpec[]>,
    default: () => []
  },
  goodsId: {type: Number, default: 0},
  goodsType: {type: Number, default: 1},
  goodsStatus: {type: Number, default: 0},
  readonly: {type: Boolean, default: false},
});

const emit = defineEmits(['change']);
const modelId = computed({
  get: () => props.modelValue,
  set: (val) => {
    let last = props.modelValue;
    emit('change', val);
    if (last != val) {
      initModelInfo(val);
    }
  },
});

/** 默认库存数量 */
const defStoreCount = ref(200);
const specItemListRef = ref();

/** 初始化 **/
onMounted(async () => {
  handleRefreshModelData();
})

/** 加载模型数据 */
const modelList = ref<GoodsModel[]>([]);
const initModeList = () => {
  modelUsableList().then(response => {
    modelList.value = response.data || []
  })
};

/** 加载模型信息 */
const formData = ref({...defGoodsModel});
const initModelInfo = (modelId: any) => {
  formData.value = {...defGoodsModel};
  if (modelId && modelId > 0) {
    // 获取模型信息
    modelInfo(modelId, {goods_id: props.goodsId}).then(response => {
      formData.value = response.data;
      generateGoodsSpecData();
    })
  }
};

watch(() => props.modelValue,
    async (val: any) => {
      initModelInfo(val)
    },
    {immediate: true}
);

/** 动态计算表头信息 */
const dynamicTableHeaders = computed(() => {
  let specList = formData.value.spec_list || []
  let headers: string[] = []
  specList.forEach(it => {
    if (it.select_ids.length > 0) {
      headers.push(it.name)
    }
  })
  return headers
});

/** 生成迪卡塔算法 */
const getDescartes = computed(() => {
  let specList = formData.value.spec_list || []
  let params: Array<number>[] = []
  specList.forEach(it => {
    if (it.select_ids.length > 0) {
      params.push(it.select_ids)
    }
  })
  return calcDescartes(params)
});

/** 生成key v map */
const specItemMap = computed(() => {
  let specList = formData.value.spec_list || []
  let specItems: GoodsModelSpecItem[] = []
  specList.forEach(it => {
    if (it.spec_items.length > 0) {
      specItems = specItems.concat(it.spec_items)
    }
  })
  let itemMap = {}
  specItems.forEach(it => {
    itemMap[it.id] = it.item
  })
  return itemMap
});

/** 商品模型列表 */
const goodsSpecList = ref<GoodsSpec[]>([]);
const generateGoodsSpecData = () => {
  let descartes = getDescartes.value;

  let goodsSpecMap = {};
  props.itemList.forEach(item => goodsSpecMap[item.spec_key] = item);

  // 生成商品模型
  let newList: GoodsSpec[] = [];
  // 处理数据生成
  descartes.forEach(it => {
    let specKey = it.join('_')
    let item: GoodsSpec;
    if (goodsSpecMap.hasOwnProperty(specKey)) {
      item = goodsSpecMap[specKey]
    } else {
      item = {
        id: 0,
        goods_id: 0,
        spec_key: specKey,
        spec_key_ids: it,
        price: 0.00,
        price_cost: 0.00,
        price_integral: 0.00,
        store_count: defStoreCount.value,
      }
    }
    newList.push(item)
  });
  // 最后设置值
  goodsSpecList.value = newList;
  // 重置分页
  handleResetPage();
};

/** 其他页面调用 获取商品规格属性 */
const getGoodsSpecs = () => {
  return goodsSpecList.value || [];
};

// 提供对外函数
defineExpose({getGoodsSpecs})

/** 列表数据 */
const tableItemList = computed(() => {
  let itemList = goodsSpecList.value || [];
  if (itemList.length > 0 && !props.readonly) {
    let temp: GoodsSpec[] = [{
      id: -1,
      goods_id: 0,
      spec_key: 'temp',
      spec_key_ids: [],
      price: undefined,
      price_cost: undefined,
      price_integral: undefined,
      store_count: defStoreCount.value,
    }]
    return temp.concat(itemList)
  }
  return itemList
});

/** 批量填充 */
const handleItemFill = (item: GoodsSpec) => {
  if (!item || item.id >= 0) return;

  // 循环填充
  goodsSpecList.value.forEach(it => {
    // 售价
    if (item.price != undefined && item.price >= 0) {
      it.price = item.price
    }
    // 成本
    if (item.price_cost != undefined && item.price_cost >= 0) {
      it.price_cost = item.price_cost
    }
    // 积分价格
    if (item.price_integral != undefined && item.price_integral >= 0) {
      it.price_integral = item.price_integral
    }
    // 库存数
    it.store_count = item.store_count
  })
};

const pageData = reactive({
  pageNum: 1,
  pageSize: 10,
});

const handleResetPage = () => {
  pageData.pageNum = 1;
  pageData.pageSize = 10;
};

const handleSizeChange = (val) => {
  pageData.pageSize = val;
};

const handleCurrentChange = (val) => {
  pageData.pageNum = val;
};

/** 商品模型弹窗操作 */
const modelFormRef = ref<any>()
const handleModelFormShow = (mode: number, id?: number) => {
  modelFormRef.value?.open(mode, id)
};

/** 处理模型数据刷新 */
const handleRefreshModelData = () => {
  initModeList();
  initModelInfo(modelId.value)
}

</script>

<style lang="scss" scoped>
.goods-info-model {

  .el-form-item {
    margin-bottom: 10px !important;
  }

  .el-select {
    max-width: 20rem;
  }

  .el-checkbox-group .el-checkbox {
    min-width: 100px;
    margin-right: 10px;
    margin-left: 0;
  }
}

.table-wrapper {
  .el-input-number {
    max-width: 9rem;
  }
}
</style>
